package com.sumer.psychology.space.application.query;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;
import com.sumer.psychology.space.domain.FriendMessage;
import com.sumer.psychology.space.domain.MessageType;

/**
 * 空间查询服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/12/9
 * Time: 16:14
 */
public class SpaceQueryApplicationService extends AbstractMongoRepository {
    private static final String DB_NAME = "sumer_message";

    @Override
    protected String dbName() {
        return DB_NAME;
    }

    /**
     * 获得好友相关消息
     *
     * @param ownerId 宿主
     * @return json
     */
    public String friendMessages(String ownerId) {
        BasicDBObject searchCondition = new BasicDBObject()
                .append("_id", ownerId)
                .append("messages.messageType", MessageType.FRIEND.toString());
        DBObject messages = db().getCollection(dbName()).findOne(searchCondition);

        if (messages == null) {
            return "";
        }

        BasicDBList messagesGroupById = FriendMessage.classifyByMessageId((BasicDBList) messages.get("messages"));
        messages.put("messages", messagesGroupById);
        return serialize(messages);
    }
}
